package com.liufei.class07;

import com.liufei.common.TreeNode;

import java.util.*;

public class Code01_BinaryTreeLevelOrderTraversalII {


    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        // 这里使用链表，而不是ArrayList，因为一直从头节点插入。链表的速度更快
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            // 一直从第一个位置插入，结果就是倒叙
            res.add(0, list);
        }
        return res;
    }

    public static void main(String[] args) {
        int testTime = 100000;
        List<Integer> arr1 = new ArrayList<>();
        long start = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            arr1.add(0, i);
        }
        System.out.println(System.currentTimeMillis() - start);

        List<Integer> arr2 = new LinkedList<>();
        start = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            arr2.add(0, i);
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}
